﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;
using InfluxDB.Models;
using AdysTech.InfluxDB.Client.Net;

namespace InfluxDB.Controllers
{
	[Route("api/[controller]")]
	public class ValuesController : Controller
	{
		private InfluxDBClient client;
		private string host = "http://localhost";
		private int port = 8096;
		public ValuesController()
		{
			client = new InfluxDBClient($"{host}:{port}");
		}
		// GET api/values
		[HttpGet]
		public async Task<IActionResult> GetAsync(string dbName, string tableName)
		{
			var l = await client.QueryMultiSeriesAsync(dbName, $"select * from {tableName}");
			return new ObjectResult(l);
		}

		// POST api/values
		[HttpPost]
		public async Task<IActionResult> PostAsync([FromBody]WriteDesc desc)
		{
			var valMixed = new InfluxDatapoint<InfluxValueField>();
			valMixed.InitializeTags(desc.tags);
			foreach (var item in desc.data)
			{
				valMixed.Fields.Add(item.Key, new InfluxValueField(item.Value));
			}
			valMixed.MeasurementName = desc.tableName;
			valMixed.UtcTimestamp = DateTime.UtcNow;
			valMixed.Precision = TimePrecision.Milliseconds;
			var r = await client.PostPointAsync(desc.dbName, valMixed);
			return Ok(r);
		}
	}
}
